<template>
  <el-container class="admin-layout">
    <el-main>
      <el-card shadow="never">
        <template #header>
          <div class="card-header">
            <span>商品管理</span>
            <el-button type="primary" @click="handleOpenDialog()">添加商品</el-button>
          </div>
        </template>
        
        <div class="filter-container">
          <el-select
            v-model="filterL1CategoryId"
            placeholder="请选择一级分类"
            clearable
            style="width: 200px; margin-right: 10px;"
          >
            <el-option
              v-for="item in l1Categories"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
          <el-select
            v-model="filterL2CategoryId"
            placeholder="请选择二级分类"
            clearable
            :disabled="!filterL1CategoryId"
            style="width: 200px;"
          >
            <el-option
              v-for="item in filterL2Options"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
          <el-input
            v-model="searchQuery"
            placeholder="按商品名称搜索"
            clearable
            style="width: 240px; margin-left: 10px;"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>

        <el-table :data="filteredProducts" v-loading="loading" style="width: 100%" @expand-change="handleExpand" row-key="id">
          <el-table-column type="expand">
            <template #default="props">
              <el-table v-loading="buyersLoadingMap[props.row.id]" :data="buyersMap[props.row.id] || []" style="width: 100%" size="small">
                <el-table-column prop="name" label="用户名"/>
                <el-table-column prop="phoneNumber" label="手机号"/>
              </el-table>
            </template>
          </el-table-column>
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column prop="name" label="商品名称" />
          <el-table-column label="分类" width="180">
             <template #default="scope">
                <span>{{ categoryMap.get(scope.row.categoryId) || '未知分类' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="价格" width="120">
            <template #default="scope">
              <span>¥{{ scope.row.price.toFixed(2) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="quantity" label="库存" width="100" />
          <el-table-column label="图片" width="100">
             <template #default="scope">
                <el-image style="width: 50px; height: 50px" :src="scope.row.imageUrl" :preview-src-list="[scope.row.imageUrl]" fit="cover" :preview-teleported="true" />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="scope">
              <el-button size="small" @click="handleOpenDialog(scope.row)">编辑</el-button>
              <el-popconfirm
                title="确定要删除这个商品吗?"
                confirm-button-text="确认"
                cancel-button-text="取消"
                @confirm="deleteProduct(scope.row.id)"
              >
                <template #reference>
                  <el-button size="small" type="danger">删除</el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </el-main>
  </el-container>

  <!-- Add/Edit Dialog -->
  <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px" @close="resetForm">
    <el-form :model="formProduct" label-width="100px" ref="formRef" :rules="rules">
      <el-form-item label="商品名称" prop="name">
        <el-input v-model="formProduct.name" />
      </el-form-item>
       <el-form-item label="一级分类" prop="l1_category_id">
         <el-select
            v-model="formProduct.l1_category_id"
            placeholder="请先选择一级分类"
            style="width: 100%;"
            @change="handleFormL1Change"
          >
            <el-option
              v-for="item in l1Categories"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
      </el-form-item>
      <el-form-item label="二级分类" prop="categoryId">
         <el-select
            v-model="formProduct.categoryId"
            placeholder="请选择二级分类"
            style="width: 100%;"
            :disabled="!formProduct.l1_category_id"
          >
            <el-option
              v-for="item in formL2Options"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
      </el-form-item>
      <el-form-item label="商品描述" prop="description">
        <el-input v-model="formProduct.description" type="textarea" />
      </el-form-item>
      <el-form-item label="价格" prop="price">
        <el-input-number v-model="formProduct.price" :precision="2" :min="0" />
      </el-form-item>
      <el-form-item label="数量" prop="quantity">
        <el-input-number v-model="formProduct.quantity" :min="0" />
      </el-form-item>
      <el-form-item label="图片URL" prop="imageUrl">
        <el-input v-model="formProduct.imageUrl" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, watch } from 'vue';
import apiClient from '../../axios/axios';
import { ElMessage, ElIcon } from 'element-plus';
import { Search } from '@element-plus/icons-vue';
import type { FormInstance, FormRules } from 'element-plus';

interface Product {
  id: number;
  name: string;
  description: string;
  price: number;
  categoryId: number;
  quantity: number;
  imageUrl: string;
}
interface Category {
  id: number;
  name: string;
  parentCategoryID: number | null;
  description: string
}
interface User { id:number; name:string; phoneNumber:string; }

const products = ref<Product[]>([]);
const loading = ref(false);
const searchQuery = ref('');

// --- Category State ---
const categoryMap = ref<Map<number, string>>(new Map());
const parentMap = ref<Map<number, number>>(new Map()); // childId -> parentId
const l1Categories = ref<Category[]>([]);
const l2CategoryGroups = ref<Map<number, Category[]>>(new Map());

// --- Filter State ---
const filterL1CategoryId = ref<number | null>(null);
const filterL2CategoryId = ref<number | null>(null);
const filterL2Options = computed(() => {
    if (!filterL1CategoryId.value) return [];
    return l2CategoryGroups.value.get(filterL1CategoryId.value) || [];
});

const filteredProducts = computed(() => {
    if (!searchQuery.value) {
        return products.value;
    }
    return products.value.filter(product =>
        product.name.toLowerCase().includes(searchQuery.value.toLowerCase())
    );
});

// --- Dialog and Form State ---
const dialogVisible = ref(false);
const dialogTitle = ref('');
const formRef = ref<FormInstance>();
const editingProductId = ref<number | null>(null);

const initialFormProductState: Omit<Product, 'id' | 'categoryId'> & { categoryId: null | number; l1_category_id: null | number } = {
  name: '',
  description: '',
  price: 0,
  categoryId: null,
  l1_category_id: null,
  quantity: 100,
  imageUrl: ''
};
const formProduct = reactive({ ...initialFormProductState });

const formL2Options = computed(() => {
    if (!formProduct.l1_category_id) return [];
    return l2CategoryGroups.value.get(formProduct.l1_category_id) || [];
});

const rules = reactive<FormRules>({
    name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
    l1_category_id: [{ required: true, message: '请选择一级分类', trigger: 'change' }],
    categoryId: [{ required: true, message: '请选择二级分类', trigger: 'change' }],
    price: [{ required: true, message: '请输入价格', trigger: 'blur' }],
    quantity: [{ required: true, message: '请输入库存数量', trigger: 'blur' }],
});

// --- Data Fetching and Processing ---
const processCategories = (categories: Category[]) => {
    const tempL1: Category[] = [];
    const tempL2Groups: Map<number, Category[]> = new Map();
    
    categories.forEach(c => {
        categoryMap.value.set(c.id, c.name);
        const parentId = c.parentCategoryID;
        if (parentId === 1) { // L1 categories have parent ID 1
            tempL1.push(c);
        } else if (typeof parentId === 'number' && parentId > 1) { // L2 categories
            parentMap.value.set(c.id, parentId);
            if (!tempL2Groups.has(parentId)) {
                tempL2Groups.set(parentId, []);
            }
            tempL2Groups.get(parentId)!.push(c);
        }
    });
    l1Categories.value = tempL1;
    l2CategoryGroups.value = tempL2Groups;
};

const fetchInitialData = async () => {
    loading.value = true;
    try {
        const [productsRes, categoriesRes] = await Promise.all([
            apiClient.get<Product[]>('/product'),
            apiClient.get<Category[]>('/category')
        ]);
        products.value = productsRes.data;
        processCategories(categoriesRes.data);
    } catch (error) {
        console.error("Failed to fetch initial data", error);
        ElMessage.error('获取初始数据失败');
    } finally {
        loading.value = false;
    }
};

const fetchProductsByCategoryId = async (categoryId: number) => {
    loading.value = true;
    searchQuery.value = ''; // Reset search query on new fetch
    try {
        const response = await apiClient.get<Product[]>(`/product/category/${categoryId}`);
        products.value = response.data;
    } catch (error) {
        console.error(`Failed to fetch products for category ${categoryId}:`, error);
        products.value = []; // Clear products on error
        ElMessage.error('获取商品列表失败');
    } finally {
        loading.value = false;
    }
};

// --- Event Handlers ---
const handleFilterChange = () => {
    const categoryToFetch = filterL2CategoryId.value || filterL1CategoryId.value || 1; // Default to 'All'
    fetchProductsByCategoryId(categoryToFetch);
};

watch(filterL1CategoryId, () => {
    filterL2CategoryId.value = null; // Reset L2 filter when L1 changes
    handleFilterChange();
});

watch(filterL2CategoryId, () => {
    handleFilterChange();
});

const handleFormL1Change = (l1Id: number | null) => {
    formProduct.categoryId = null;
};

const handleOpenDialog = (product?: Product) => {
    if (product) {
        dialogTitle.value = '编辑商品';
        editingProductId.value = product.id;
        const parentId = parentMap.value.get(product.categoryId);

        Object.assign(formProduct, {
            ...product,
            l1_category_id: parentId || null
        });
    } else {
        dialogTitle.value = '添加商品';
        editingProductId.value = null;
        resetForm();
    }
    dialogVisible.value = true;
};

const resetForm = () => {
    Object.assign(formProduct, initialFormProductState);
    editingProductId.value = null;
    if (formRef.value) {
        formRef.value.clearValidate();
    }
};

const submitForm = async () => {
    if (!formRef.value) return;
    await formRef.value.validate(async (valid) => {
        if (valid) {
            try {
                const { l1_category_id, ...payload } = formProduct;

                if (editingProductId.value) {
                    await apiClient.put(`/product/${editingProductId.value}`, payload);
                    ElMessage.success('商品更新成功');
                } else {
                    await apiClient.post('/product', payload);
                    ElMessage.success('商品添加成功');
                }
                dialogVisible.value = false;
                handleFilterChange(); // Refresh the product list based on current filter
            } catch (error) {
                console.error('Form submission error:', error);
                ElMessage.error('操作失败，请重试');
            }
        }
    });
};

const deleteProduct = async (id: number) => {
    try {
        await apiClient.delete(`/product/${id}`);
        ElMessage.success('商品删除成功');
        handleFilterChange(); // Refresh the product list
    } catch (error) {
        console.error('Failed to delete product:', error);
        ElMessage.error('删除失败');
    }
};

const buyersMap = ref<Record<number, User[]>>({});
const buyersLoadingMap = ref<Record<number, boolean>>({});

const handleExpand = async (row: Product, expandedRows: Product[]) => {
  if (!expandedRows.includes(row)) return; // only on expand open
  if (buyersMap.value[row.id]) return; // already loaded
  buyersLoadingMap.value[row.id] = true;
  try {
    const res = await apiClient.get<User[]>(`/user/product/${row.id}/buyers`);
    buyersMap.value[row.id] = res.data;
  } catch (e) {
    ElMessage.error('获取购买用户失败');
    buyersMap.value[row.id] = [];
  } finally {
    buyersLoadingMap.value[row.id] = false;
  }
};

onMounted(() => {
    fetchInitialData();
});
</script>

<style scoped>
.admin-layout {
  height: 100%;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.filter-container {
  margin-bottom: 20px;
}
</style>
